#!/usr/bin/env node

//上传文件
const http = require('http'),
      log = console.log
      fs = require('fs');

http.createServer((req,res)=>{
    log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
    log();
    let data = '',fileName = '',fileContent='';
    if(req.url === '/'){
      if(req.method === 'POST'){
          req.setEncoding('binary');
          req.on('data',chunk=> data +=chunk);
          req.on('end',()=>{
              log(data);
              data = data.split('\r\n');    
              fileName = data[1].split(';');
              fileName = fileName[fileName.length-1].split('=');
              fileName = fileName[1];
              fileName = fileName.substring(1,fileName.length-1);
              log('file name:',fileName);
              fileContent = data[4];
              log(fileContent);
              fs.writeFileSync(fileName,fileContent,{'encoding': 'binary'});
              res.end('ok');
          });
      }else if(req.method === 'GET'){
          res.end('ok')
      }else{
          res.statusCode = 404;
          res.end('Request method not supported!')
      }      
    }else{
        res.statusCode = 404;
        res.end('Resource not found！')  
    }
}).listen(8080);

